package io.renren.modules.file.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import io.renren.common.utils.R;
import io.renren.modules.file.dto.input.ProveEntityInput;
import io.renren.modules.img.entity.ProveEntity;
import io.renren.modules.img.service.ProveService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author liangbaigao
 * @Date 2022/10/18 8:19
 */
@RestController
@Api(tags = "文件上传接口")
@RequestMapping("/upload")
public class FileUpload {

    @Resource
    private ProveService proveService;

     /**
     * 上传pdf
     * @return
     */
    @ApiOperation("上传pdf文件")
    @PostMapping("/uploadPdf")
    @Transactional(rollbackFor = Exception.class)
    public R uploadPdf(HttpServletRequest request,
                       @RequestPart("pdf") MultipartFile pdf, ProveEntityInput input)
            throws ServletException, IOException {
        //当前登录用户
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        // 查询数据库，看试卷id 用户id 题号是否有数据 （校验用户是否重复上传）
        LambdaQueryChainWrapper<ProveEntity> eq = proveService.lambdaQuery().
                eq(ProveEntity::getQuestionId, input.getQuestionId()).
                eq(ProveEntity::getUser, principal.getUserId()).
                eq(ProveEntity::getNumber,input.getNumber());
        List<Object> objects = proveService.listObjs(eq);
        if(objects.size()!=0){
            return R.error("请勿重复上传");
        }
        int i = 0;
        for (Part part : request.getParts()) {
            if(i==1){
                continue;
            }
            String address = "/www/wwwroot/pdf";
            // 获取文件类型
            String contentType = part.getContentType();
            String[] split = contentType.split("/");
            if(!"pdf".equals(split[1])){
                return R.error("请上传pdf文件");
            }
            if(part.getSize() <= 0 ){
                return R.error("请重新上传");
            }
            // 不存在则创建文件夹
            SimpleDateFormat datePattern = new SimpleDateFormat("yyyy-MM-dd");
            String format = datePattern.format(new Date());
            address += "\\" + format;
            File filePath = new File(address);
            if (!filePath.exists() && !filePath.isDirectory()) {
                System.out.println("目录不存在，创建目录:" + filePath);
                filePath.mkdirs();
            }
            // 文件名称
            String originalFilename =
                    pdf.getOriginalFilename();
            assert ObjectUtil.isNotNull(originalFilename);
            File targetFile = new File(address, originalFilename);
            // 获取文件路径
            String absolutePath = targetFile.getAbsolutePath();
            ProveEntity proveEntity=new ProveEntity();
            proveEntity.setImg(absolutePath);
            proveEntity.setUser(Math.toIntExact(principal.getUserId()));
            proveEntity.setUsername(principal.getUsername());
            proveEntity.setQuestionId(input.getQuestionId());
            proveEntity.setNumber(input.getNumber());
            proveService.save(proveEntity);
            try {
                pdf.transferTo(targetFile);
                i++;
            }catch (Exception e){
                e.printStackTrace();
                return R.error("文件上传失败");
            }
        }
        return R.ok("文件上传成功");
    }

    /**
     *
     * @param input
     * @return
     */
    @ApiOperation("查看pdf文件")
    @PostMapping("/showPdf")
    public R showPdf(@RequestBody @Valid ProveEntityInput input){
        //当前登录用户
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        // 查询数据库，看试卷id 用户id 题号是否有数据
        LambdaQueryChainWrapper<ProveEntity> eq = proveService.lambdaQuery().
                eq(ProveEntity::getQuestionId, input.getQuestionId()).
                eq(ProveEntity::getUser, principal.getUserId()).
                eq(ProveEntity::getNumber,input.getNumber());
        List<ProveEntity> proveEntities =
                proveService.getBaseMapper().selectList(eq);
        String img = null;
        if(proveEntities.size() == 0) return R.error();
        for (ProveEntity proveEntity : proveEntities) {
            img = proveEntity.getImg();
        }
        return  R.ok("图片地址为:"+img);
    }
}
